#coding:utf-8
from pygments import highlight 
from pygments.lexers import get_lexer_by_name, PhpLexer 
from pygments.formatters import HtmlFormatter 
from pygments.util import ClassNotFound 
from django import template
from django.template.defaultfilters import stringfilter
from django.utils.safestring import mark_safe
import markdown
register = template.Library() 
 
@register.filter 
def highlight_code(code,style): 
  if code is not None: 
    print 'style',style
    try: 
      # startinline is for PhpLexer so that it doesn't 
      # require a <?php 
      lexer = get_lexer_by_name('Python', encoding='utf-8', stripall=True, startinline=True)
      print lexer 
    except ClassNotFound:
      print 'eeeeeeeeeeeeeee'
      lexer = get_lexer_by_name('text') 
    formatter = HtmlFormatter(encoding='utf-8', style=style, linenos='table', cssclass='highlight', lineanchors="line")
    print formatter.get_style_defs('.highlight') 
    print 'code',highlight(code, lexer, formatter)
    return highlight(code, lexer, formatter)   
  else: 
    return code

@register.filter(is_safe=True)  # 注册template filter
@stringfilter  # 希望字符串作为参数
def custom_markdown(value):
    return mark_safe(markdown.markdown(value,extensions=['markdown.extensions.fenced_code','markdown.extensions.footnotes','markdown.extensions.smarty','markdown.extensions.nl2br','markdown.extensions.toc','markdown.extensions.wikilinks','markdown.extensions.attr_list','markdown.extensions.abbr','markdown.extensions.sane_lists','markdown.extensions.codehilite','markdown.extensions.tables'],safe_mode=True,enable_attributes=False)) 
